/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.pvacameras.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.security.SignatureException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.google.pvacameras.server.config.Config;
import com.google.wallet.online.jwt.Cart;
import com.google.wallet.online.jwt.FullWalletBody;
import com.google.wallet.online.jwt.FullWalletRequest;
import com.google.wallet.online.jwt.LineItem;
import com.google.wallet.online.jwt.MaskedWalletResponse;
import com.google.wallet.online.jwt.util.WalletOnlineService;

/**
 * This servlet handles the Masked Wallet Response JWT and decrypts the
 * encrypted shipping and billing information using the decrypter class. Then it
 * renders the order confirmation page and generates the Full WalletRequest.
 * 
 * Templating uses Velocity Template
 * 
 * @author David Peng (gpeng@google.com)
 */

public class ConfirmServlet extends HttpServlet {
	private static final long serialVersionUID = 2294124125211846176L;

	/**
	 * Get handler forwards request to post handler.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		doPost(req, resp);
	}

	/**
	 * Post handler renders the template generates the FullWalletRequest and
	 * deciphered MaskedWalletResponse. Then injects these JWT into the template.
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		try {

			// Get post parameters
			String description = req.getParameter("description");
			String quantity = req.getParameter("quantity");
			String unitprice = req.getParameter("unitprice");
			String gid = req.getParameter("gid");

			// Apply the utility service for conversion between Wallet Java objects
			// and JWT
			WalletOnlineService ows = new WalletOnlineService(Config.getMerchantId(),
					Config.getMerchantSecret());

			// Parse the MaskedWallet Response into JsonToken object
			MaskedWalletResponse mwrResponse = ows.jwtToJava(
					MaskedWalletResponse.class, req.getParameter("maskedWallet"));

			// Create the LineItem object
			LineItem item = new LineItem(description, Integer.valueOf(quantity),
					unitprice);
			item.setIsDigital(false);
			LineItem tax = new LineItem();
			tax.setDescription("Sales Taxes");
			tax.setTotalPrice("8.00");
			LineItem shipping = new LineItem();
			shipping.setDescription("Overnight Shipping");
			shipping.setTotalPrice("9.99");

			// Create the cart object and injects the generated LineItem object
			Cart cart = new Cart(Config.CURRENCY);
			cart.addItem(item);
			cart.addItem(tax);
			cart.addItem(shipping);

			// Create the FullWalletBody using the generated cart object
			FullWalletBody fwb = new FullWalletBody(cart);
			String origin = Config.getDomain(req);
			fwb.setOrigin(origin);
			fwb.setGoogleTransactionId(gid);

			// Create the FullWalletRequest object using the generated FullWalletBody
			// object
			FullWalletRequest fwr = new FullWalletRequest(fwb);

			// So we don't write to velocity.log
			Velocity.setProperty("runtime.log.logsystem.class",
					"org.apache.velocity.runtime.log.NullLogChute");

			// Escape HTML
			Velocity.setProperty("eventhandler.referenceinsertion.class",
					"org.apache.velocity.app.event.implement.EscapeHtmlReference");
			Velocity.setProperty("eventhandler.escape.html.match", "/.*/");

			// Initialize Velocity Templates
			Velocity.init();
			VelocityContext context = new VelocityContext();

			// Get the response output stream PrintWriter
			PrintWriter pw;
			pw = resp.getWriter();

			// Injects the information from the masked Wallet Response, change Wallet and the
			// FullWalletRequest JWT into
			// the template
			context.put("shippingName", mwrResponse.getResponse().getShip()
					.getShipping_address().getName());
			context.put("shippingAddress1", mwrResponse.getResponse().getShip()
					.getShipping_address().getAddress1());
			context.put("shippingCity", mwrResponse.getResponse().getShip()
					.getShipping_address().getCity());
			context.put("shippingState", mwrResponse.getResponse().getShip()
					.getShipping_address().getState());
			context.put("shippingPost", mwrResponse.getResponse().getShip()
					.getShipping_address().getPostal_code());
			context.put("buyerEmail", mwrResponse.getResponse().getEmail());
			context.put("buyerBilling", mwrResponse.getResponse().getPay()
					.getDescription());
			context.put("changeJwt", req.getParameter("changeJwt"));
			context.put("fullWalletJwt", ows.javaToJwt(fwr));
			context.put("totalPrice", Integer.parseInt(unitprice)+9.99+8);
			context.put("itemPrice", unitprice);

			// Render the template and output to print stream
			Velocity.mergeTemplate("confirm.vm", "UTF-8", context, pw);
			pw.flush();
			pw.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
